package cn.toolck.minitomcat.passer;

import cn.toolck.minitomcat.classLoader.MyClassLoader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @ClassName Passer
 * @Description 文件解析的父类封装获取document
 * @Author Toolck Rin
 * @Date 2021/3/18 0:42
 * @Version 1.0
 **/
public abstract class Passer {
    private String fileName;
    private Document document;
    private ClassLoader classLoader;

    public Passer(String fileName) {
        this(fileName, Thread.currentThread().getContextClassLoader());
    }

    public Passer(String fileName, ClassLoader classLoader) {
        this.classLoader = classLoader;
        this.fileName = fileName;
        init();
    }

    private void init() {
        try {
            InputStream resourceAsStream = null;
            if (!(classLoader instanceof MyClassLoader)) {
                resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
            } else {
                File file = new File(fileName);
                resourceAsStream = new FileInputStream(file);
            }
            SAXReader saxReader = new SAXReader();
            document = saxReader.read(resourceAsStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public Document getDocument() {
        return document;
    }

    public void setDocument(Document document) {
        this.document = document;
    }

    public ClassLoader getClassLoader() {
        return classLoader;
    }

    public void setClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }
}
